﻿using DiLe.Mes.Application.Common.Equipment;
using DiLe.Mes.Model.Cloud.Dashboard.Equipment;
using DiLe.Mes.Model.Cloud.Dashboard.Statistics;
using DiLe.Mes.Model.Common.Abnormal.Entity;
using DiLe.Mes.Model.Common.WorkOrder.Entity;
using DiLe.Mes.Model.Common.WorkOrder.Relation;
using DiLe.Mes.Model.Local.Entity;
using MapleLeaf.Core.Entity;
using MapleLeaf.Core.EventBus;
using MapleLeaf.Core.Serilog;

namespace DiLe.Mes.Cloud.Expansion
{
    /// <summary>
    /// 
    /// </summary>
    public class DataReceive {
        private readonly static ISqlSugarClient _masterDB = SqlSugarHelper.MasterDb;
        private readonly static ISqlSugarClient _cloudDB = SqlSugarHelper.CloudDb;
        private readonly static EquipmentManageClient _equipmentManage = AppHelper.GetService<EquipmentManageClient>();
        private readonly static string[] separator = [","];
        //private static readonly object thisLock = new();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static void SaveData(MessageModel model) {
            if (model.SendMsg.IsNullOrEmpty()) {
                return;
            }
            _ = model.MsgSign switch {
                "AOIPointInfo" => ReveiveAOIPointInfo(model),
                "OtherPointInfo" => ReveiveOtherPointInfo(model),
                "EMPointInfo" => ReveiveEMPointInfo(model),
                "PMPointInfo" => ReveiveFMPointInfo(model),
                "TrimlPointInfo" => ReveiveTrimPointInfo(model),
                "StartWorkRecord" => ReveiveStartWorkRecord(model.SendMsg!, model.AppId),
                "StartWorkRecord2MouldInfo" => ReveiveStartWorkRecord2MouldInfo(model.SendMsg!, model.AppId),
                "ReportWorkRecord" => ReveiveReportWorkRecord(model.SendMsg!, model.AppId),
                _ => ReveivePointInfo(model),
            };
        }
        #region 流量表
        /// <summary>
        /// 接收流量表
        /// </summary>
        private static int ReveiveFMPointInfo(MessageModel model) {
            string id = Guid.NewGuid().ToString();
            try {
                SerilogLogHelper.WriteSystemLog($"流量表plc开始接收=>{id}：{model.SendMsg}");
                var pm_lmodels = JsonConvert.DeserializeObject<List<FMPointInfoEntity>>(model.SendMsg);
                if (pm_lmodels == null || pm_lmodels.None()) {
                    return 0;
                }
                var pm_cmodels = new List<CloudFMPointInfoEntity>();
                foreach (var item in pm_lmodels) {
                    var m = item.Adapt<CloudFMPointInfoEntity>();
                    m.AcquisitionTime = item.CreateTime;
                    m.Id = 0;
                    m.FactoryId = model.AppId;
                    pm_cmodels.Add(m);
                }
                var pm_keys = pm_cmodels.Select(p => p.DeviceNo).Distinct().ToList();
                var pm_where = Expressionable.Create<CloudFMPointInfoEntity>();
                pm_where.And(p => p.DataUploadDate == DateTime.Now.Date);
                pm_where.AndIF(!pm_keys.None(), p => pm_keys.Contains(p.DeviceNo));
                pm_where.AndIF(model.AppId > 0, p => p.FactoryId == model.AppId);
                //删除
                int res = _cloudDB.Deleteable<CloudFMPointInfoEntity>().Where(pm_where.ToExpression()).ExecuteCommand();
                //插入
                res = _cloudDB.Insertable(pm_cmodels).ExecuteCommand();
                SerilogLogHelper.WriteSystemLog($"流量表plc接收完成=>{id}");
                return res;
            } catch (Exception ex) {
                var str = $"流量表plc接收失败=>{id}：{ex.Message}";
                SerilogLogHelper.WriteSystemErrorLog(str);
                return 0;
            }
        }
        #endregion
        #region 电表
        /// <summary>
        /// 接收电表
        /// </summary>
        private static int ReveiveEMPointInfo(MessageModel model) {
            string id = Guid.NewGuid().ToString();
            try {
                SerilogLogHelper.WriteSystemLog($"电表plc开始接收=>{id}：{model.SendMsg}");
                var em_lmodels = JsonConvert.DeserializeObject<List<EMPointInfoEntity>>(model.SendMsg);
                if (em_lmodels == null || em_lmodels.None()) {
                    return 0;
                }
                var em_cmodels = new List<CloudEMPointInfoEntity>();
                foreach (var item in em_lmodels) {
                    var m = item.Adapt<CloudEMPointInfoEntity>();
                    m.AcquisitionTime = item.CreateTime;
                    m.Id = 0;
                    m.FactoryId = model.AppId;
                    em_cmodels.Add(m);
                }
                var em_keys = em_cmodels.Select(p => p.DeviceNo).Distinct().ToList();
                var em_where = Expressionable.Create<CloudEMPointInfoEntity>();
                em_where.And(p => p.DataUploadDate == DateTime.Now.Date);
                em_where.AndIF(!em_keys.None(), p => em_keys.Contains(p.DeviceNo));
                em_where.AndIF(model.AppId > 0, p => p.FactoryId == model.AppId);
                //删除
                int res = _cloudDB.Deleteable<CloudEMPointInfoEntity>().Where(em_where.ToExpression()).ExecuteCommand();
                //插入
                res = _cloudDB.Insertable(em_cmodels).ExecuteCommand();
                SerilogLogHelper.WriteSystemLog($"电表plc接收完成=>{id}");
                return res;
            } catch (Exception ex) {
                var str = $"电表plc接收失败=>{id}：{ex.Message}";
                SerilogLogHelper.WriteSystemErrorLog(str);
                return 0;
            }
        }
        #endregion


        #region 成型机
        /// <summary>
        /// 接收成型机
        /// </summary>
        private static int ReveivePointInfo(MessageModel model) {
            string id = Guid.NewGuid().ToString();
            try {
                SerilogLogHelper.WriteSystemLog($"成型机plc开始接收=>{id}：{model.SendMsg}");
                var lmodels = JsonConvert.DeserializeObject<List<PointInfoEntity>>(model.SendMsg);
                if (lmodels == null || lmodels.None()) {
                    return 0;
                }
                var cmodels = new List<CloudPointInfoEntity>();
                foreach (var item in lmodels) {
                    var m = item.Adapt<CloudPointInfoEntity>();
                    m.AcquisitionTime = item.CreateTime;
                    m.Id = 0;
                    m.FactoryId = model.AppId;
                    cmodels.Add(m);
                }
                var keys = cmodels.Select(p => p.DeviceNo).Distinct().ToList();
                var where = Expressionable.Create<CloudPointInfoEntity>();
                where.AndIF(!keys.None(), p => keys.Contains(p.DeviceNo));
                where.And(p => p.DataUploadDate == DateTime.Now.Date);
                where.AndIF(model.AppId > 0, p => p.FactoryId == model.AppId);
                int res = _cloudDB.Deleteable<CloudPointInfoEntity>().Where(where.ToExpression()).ExecuteCommand();
                res = _cloudDB.Insertable(cmodels).ExecuteCommand();
             
                SerilogLogHelper.WriteSystemLog($"成型机plc接收完成=>{id}");
                return res;
            } catch (Exception ex) {
                var str = $"成型机plc接收失败=>{id}：{ex.Message}";
                SerilogLogHelper.WriteSystemErrorLog(str);
                return 0;
            }
        }
      

        #endregion
        #region 1311
        /// <summary>
        /// 接收1311
        /// </summary>
        private static int ReveiveOtherPointInfo(MessageModel model) {

            string id = Guid.NewGuid().ToString();
            try {
                SerilogLogHelper.WriteSystemLog($"1311plc开始接收=>{id}：{model.ToJosn()}");
                var lmodels = JsonConvert.DeserializeObject<List<OtherPointInfoEntity>>(model.SendMsg);
                if (lmodels == null || lmodels.None()) {
                    return 0;
                }
                var cmodels = new List<CloudOtherPointInfoEntity>();
                foreach (var item in lmodels) {
                    var m = item.Adapt<CloudOtherPointInfoEntity>();
                    if (item.CreateTime != null) {
                        m.AcquisitionTime = ConvertTime(model.ServerTimeZone, item.CreateTime.Value);
                    }
                    m.Id = 0;
                    m.FactoryId = model.AppId;
                    cmodels.Add(m);
                }
                var keys = cmodels.Select(p => p.DeviceNo).Distinct().ToList();
                var where = Expressionable.Create<CloudOtherPointInfoEntity>();
                where.And(p => p.DataUploadDate == DateTime.Now.Date);
                where.AndIF(!keys.None(), p => keys.Contains(p.DeviceNo));
                where.AndIF(model.AppId > 0, p => p.FactoryId == model.AppId);
                //删除
                _cloudDB.Deleteable<CloudOtherPointInfoEntity>().Where(where.ToExpression()).ExecuteCommand();
                //插入
                var res = _cloudDB.Insertable(cmodels).ExecuteCommand();
                SerilogLogHelper.WriteSystemLog($"1311plc接收完成=>{id}");
                return res;
            } catch (Exception ex) {
                var str = $"1311plc接收失败=>{id}：{ex.Message}";
                SerilogLogHelper.WriteSystemErrorLog(str);
                return 0;
            }

        }
        #endregion
        #region 切箍边
        /// <summary>
        /// 切箍边
        /// </summary>
        private static int ReveiveTrimPointInfo(MessageModel model) {
            string id = Guid.NewGuid().ToString();
            try {
                SerilogLogHelper.WriteSystemLog($"切箍边plc开始接收=>{id}：{model.SendMsg}");
                var lmodels = JsonConvert.DeserializeObject<List<TrimPointInfoEntity>>(model.SendMsg);
                if (lmodels == null || lmodels.None()) {
                    return 0;
                }
                var cmodels = new List<CloudTrimPointInfoEntity>();
                foreach (var item in lmodels) {
                    var m = item.Adapt<CloudTrimPointInfoEntity>();
                    m.AcquisitionTime = item.CreateTime;
                    m.Id = 0;
                    m.FactoryId = model.AppId;
                    cmodels.Add(m);
                }
                var keys = cmodels.Select(p => p.DeviceNo).Distinct().ToList();
                var where = Expressionable.Create<CloudTrimPointInfoEntity>();
                where.And(p => p.DataUploadDate == DateTime.Now.Date);
                where.AndIF(!keys.None(), p => keys.Contains(p.DeviceNo));
                where.AndIF(model.AppId > 0, p => p.FactoryId == model.AppId);
                //删除
                _ = _cloudDB.Deleteable<CloudTrimPointInfoEntity>().Where(where.ToExpression()).ExecuteCommand();
                //插入
                var res = _cloudDB.Insertable(cmodels).ExecuteCommand();
                SerilogLogHelper.WriteSystemLog($"切箍边plc接收完成=>{id}");
                return res;
            } catch (Exception ex) {
                var str = $"切箍边plc接收失败：{ex.Message}";
                SerilogLogHelper.WriteSystemErrorLog(str);
                return 0;
            }
        }
        #endregion
        #region AOI
        /// <summary>
        /// 接收AOI PLC数据
        /// </summary>
        private static int ReveiveAOIPointInfo(MessageModel model) {
            string id = Guid.NewGuid().ToString();
            try {
                SerilogLogHelper.WriteSystemLog($"AOI PLC开始接收=>{id}：{model.SendMsg}");
                var aoi_lmodels = JsonConvert.DeserializeObject<List<AOIPointInfoEntity>>(model.SendMsg);
                if (aoi_lmodels == null) {
                    return 0;
                }
                var aoi_cmodels = new List<CloudAOIPointInfoEntity>();
                foreach (var item in aoi_lmodels) {
                    var m = item.Adapt<CloudAOIPointInfoEntity>();
                    m.AcquisitionTime = item.CreateTime;
                    m.Id = 0;
                    m.FactoryId = model.AppId;
                    aoi_cmodels.Add(m);
                }
                var aoi_keys = aoi_cmodels.Select(p => p.DeviceNo).Distinct().ToList();
                var whereExp = Expressionable.Create<CloudAOIPointInfoEntity>();
                whereExp.And(p => p.DataUploadDate == DateTime.Now.Date);
                whereExp.AndIF(!aoi_keys.None(), p => aoi_keys.Contains(p.DeviceNo));
                whereExp.AndIF(model.AppId > 0, p => p.FactoryId == model.AppId);
                //删除

                int res = _cloudDB.Deleteable<CloudAOIPointInfoEntity>().Where(whereExp.ToExpression()).ExecuteCommand();
                //插入
                res = _cloudDB.Insertable(aoi_cmodels).ExecuteCommand();
                SerilogLogHelper.WriteSystemLog($"AOI PLC接收完成=>{id}");
                return res;
            } catch (Exception ex) {
                var str = $"AOI PLC接收失败=>{id}：{ex.Message}";
                SerilogLogHelper.WriteSystemErrorLog(str);
                return 0;
            }
        }
        #endregion


        #region  开工报工数据
        /// <summary>
        /// 接收开工数据
        /// </summary>
        /// <returns></returns>
        private static int ReveiveStartWorkRecord(string data, long? appid) {
            try {
                var models = JsonConvert.DeserializeObject<List<StartWorkRecordEntity>>(data);
                if (models.None()) {
                    return 0;
                }
                models?.ForEach(x => x.FactoryId = appid);
                _masterDB.Deleteable(models).ExecuteCommand();
                //插入
                var res = _masterDB.Insertable(models).ExecuteCommand();
                return res;
            } catch (Exception ex) {
                var str = $"开工数据接收失败：{ex.Message}";
                SerilogLogHelper.WriteSystemErrorLog(str);
                return 0;
            }
        }
        /// <summary>
        /// 接收开工和模具
        /// </summary>
        /// <returns></returns>
        private static int ReveiveStartWorkRecord2MouldInfo(string data, long? appid) {
            try {
                var models = JsonConvert.DeserializeObject<List<StartWorkRecord2MouldInfoEntity>>(data);
                if (models.None()) {
                    return 0;
                }
                models?.ForEach(x => x.FactoryId = appid);
                var res = _masterDB.Deleteable(models).ExecuteCommand();
                //插入
                res = _masterDB.Insertable(models).ExecuteCommand();
                return res;
            } catch (Exception ex) {
                var str = $"开工和模具接收失败：{ex.Message}";
                SerilogLogHelper.WriteSystemErrorLog(str);
                return 0;
            }

        }
        /// <summary>
        /// 接收报工数据
        /// </summary>
        /// <returns></returns>
        private static int ReveiveReportWorkRecord(string data, long? appid) {
            try {
                var models = JsonConvert.DeserializeObject<List<ReportWorkRecordEntity>>(data);
                if (models.None()) {
                    return 0;
                }
                models?.ForEach(x => x.FactoryId = appid);
                //插入
                _masterDB.Deleteable(models).ExecuteCommand();
                var res = _masterDB.Insertable(models).ExecuteCommand();
                return res;
            } catch (Exception ex) {
                var str = $"报工接收失败：{ex.Message}";
                SerilogLogHelper.WriteSystemErrorLog(str);
                return 0;
            }
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static DateTime ConvertTime(TimeZoneInfo timeZone, DateTime dateTime) {
            DateTime chinaTime = TimeZoneInfo.ConvertTime(dateTime, timeZone, TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"));
            return chinaTime;
        }
    }
}
